package com.qf.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsGrouponRulesMapper;
import com.qf.pojo.DtsGrouponRules;
import com.qf.service.AdminGrouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class AdminGrouponServiceImpl implements AdminGrouponService {

    @Autowired
    private DtsGrouponRulesMapper dtsGrouponRulesMapper;

    @Override
    public IPage<DtsGrouponRules> selectGrouponList(Integer page, Integer limit, Integer goodsId, String sort, String order) {

        IPage<DtsGrouponRules> iPage = new Page<>(page,limit);

        QueryWrapper<DtsGrouponRules> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted" ,false);
        wrapper.orderByAsc("asc".equalsIgnoreCase(order),sort);
        wrapper.orderByDesc("desc".equalsIgnoreCase(order),sort);
        wrapper.eq(goodsId!= null, "goods_id", goodsId);

        IPage<DtsGrouponRules> result = dtsGrouponRulesMapper.selectPage(iPage, wrapper);
        return result;
    }

    @Override
    public DtsGrouponRules insertGroupon(DtsGrouponRules dtsGrouponRules) {

        dtsGrouponRules.setAddTime(new Date());
        dtsGrouponRules.setUpdateTime(new Date());
        dtsGrouponRules.setDeleted(false);
        dtsGrouponRules.setExpireTime(new Date());

        dtsGrouponRulesMapper.insert(dtsGrouponRules);

        QueryWrapper<DtsGrouponRules> wrapper = new QueryWrapper<>();
        wrapper.select("id");
        wrapper.eq("goods_id" , dtsGrouponRules.getGoodsId());
        DtsGrouponRules result = dtsGrouponRulesMapper.selectOne(wrapper);
        dtsGrouponRules.setId(result.getId());
        return dtsGrouponRules;
    }

    @Override
    public void updateGroupon(DtsGrouponRules dtsGrouponRules) {
        dtsGrouponRules.setUpdateTime(new Date());
        dtsGrouponRulesMapper.updateById(dtsGrouponRules);
    }

    @Override
    public void deleteGroupon(Integer id) {
        DtsGrouponRules dtsGrouponRules = new DtsGrouponRules();
        dtsGrouponRules.setId(id);
        dtsGrouponRules.setDeleted(true);
        dtsGrouponRulesMapper.updateById(dtsGrouponRules);
    }
}
